package com.sm.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import com.sm.model.Assess;
import com.sm.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sm.service.AssessService;
import com.sm.service.OrderService;
import com.sm.util.CommonUtil;
import com.sm.util.Msg;

@Controller
@RequestMapping("/assess")
public class AssessController {

    @Autowired
    private AssessService assessService;
    @Autowired
    private OrderService orderService;

    /**
     * 添加评论
     *
     * @param userId
     * @param goodsId
     * @param assessContent
     * @param pic
     * @param assessStar
     * @return
     */
    @RequestMapping("/addAssess")
    @ResponseBody
    public Msg addAssess(Integer orderId, Integer userId, Integer goodsId, String assessContent, MultipartFile pic, Integer assessStar) {
        if (orderId == null || userId == null || goodsId == null || assessContent == null || assessStar == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        String assessPic = null;
        if (pic != null) {
            try {
                assessPic = CommonUtil.saveFile(pic);
            } catch (IllegalStateException e) {
                return Msg.fail().add("msg", "图片上传失败");
            } catch (IOException e) {
                return Msg.fail().add("msg", "图片上传失败");
            }
        }
        Assess a = new Assess();
        a.setAssessContent(assessContent);
        a.setAssessPic(assessPic);
        a.setAssessStar(assessStar);
        a.setAssessTime(new Date());
        a.setGoodsId(goodsId);
        a.setUserId(userId);
        int b = assessService.insertSelective(a);
        if (b == 1) {
            Order order = orderService.selectByPrimaryKey(orderId);
            order.setOrderStatus(2);
            int c = orderService.updateByPrimaryKeySelective(order);
            if (c == 1) {
                return Msg.success();
            } else {
                return Msg.fail();
            }

        } else {
            return Msg.fail();
        }
    }

    /**
     * 通过商品id查评论
     *
     * @param goodsId
     * @return
     */
    @RequestMapping("/selectAssessByGoodsId")
    @ResponseBody
    public Msg selectAssessByGoodsId(Integer goodsId) {
        if (goodsId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        List<Assess> list = assessService.selectByGoodsId(goodsId);
        return Msg.success().add("list", list);
    }
}
